<?php

declare(strict_types=1);

namespace app\common\dao\sys;

use app\common\model\sys\SysUser;
use app\common\traits\DaoTrait;

/**
 * 系统用户 - DAO
 * @author:kaige
 * @date:2022-06-12
 * @copyright ©2022 泉州市盛筑信息科技有限公司 版权所有
 */
class UserDao
{
  // 当前操作的模型
  protected $model = null;

  // 对应模型的主键，默认为id
  protected $pk = 'id';

  // 对应模型默认查询的字段
  protected $name = 'un';

  // 对应模型允许查询的字段(默认全部查询)
  protected $allowField = ['*'];

  // 允许单字段更新
  protected $uaField = ['status'];

  // 查询结果-要隐藏的字段 默认空数组
  protected $hideField = ['pwd', 'sz_salt'];

  public function __construct()
  {
    $this->model = new SysUser();
  }
  use DaoTrait;

  /**
   * 根据用户ID获取公司ID
   */
  public function getCompanyIdByUserId($uid)
  {
    return $this->model->where('id', $uid)->value('company_id');
  }

  /**
   * 查重
   */
  public function userExist($username)
  {
    return $this->model->withTrashed()->where(['un' => $username])->count() > 0;
  }

  /**
   * 获取员工列表
   * @return array
   */
  public function getEmployeeList()
  {
    return $this->model->field('id,real_name,real_name as name,phone')->where(['status' => 1])->order('sort asc')->select()->toArray(); // 整个name，个别片断需要
  }

  /**
   * 获取员工列表 -API用
   * @return array
   */
  public function getEmployeeListUseAPI()
  {
    return $this->model->field('id,real_name,real_name as name,avatar,dept_id,dept_id_name,sign,online,phone,pingyin_name')
      ->where([['status', '=', 1]])->order('pingyin_name asc,sort asc')->select()->toArray();
  }


  /**
   * 依ID获取用户姓名
   * @return string
   */
  public function getEmployeeName($id)
  {
    return $this->model->field('id,real_name as name,phone')->where(['status' => 1, 'id' => $id])->value('real_name');
  }
  /**
   * 依ID获取用户信息
   * @return array
   */
  public function getEmployeeInfo($id)
  {
    $data = $this->model->field('id,real_name as name,real_name,phone,dept_id,dept_id_name,company_id,avatar')->where(['status' => 1, 'id' => $id])->find();
    if ($data) {
      return $data->toArray();
    }
    return [];
  }

  /**
   * 取根据部门下所有人员
   */
  public function getDeptUserList($dept_id = 0)
  {
    return $this->model->field('id,real_name,real_name as name,avatar,dept_id,dept_id_name,sign,online,phone')->where('dept_id', $dept_id)->select()->toArray();
  }

  /**
   * 根据公司ID获取用户ID集
   */
  public function getUserIdByCompanyId($company_id = 0)
  {
    $where = [];
    $where[] = ['company_id', '=', $company_id];
    $where[] = ['status', '=', 1];
    return $this->model->where($where)->column('id');
  }

  /**
   * 根据部门ID获取用户ID集
   */
  public function getUserIdByDeptId($dept_id = 0)
  {
    $where = [];
    $where[] = ['dept_id', '=', $dept_id];
    $where[] = ['status', '=', 1];
    return $this->model->where($where)->column('id');
  }
}
